package com.tgy.jwt.service.impl;

import com.tgy.jwt.consts.GlobalConsts;
import com.tgy.jwt.service.ITokenService;
import com.tgy.jwt.token.TokenMgr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author tanggy
 * @date 2022/4/29 16:14
 */
@Service
@Slf4j
@EnableScheduling
public class TokenServiceImpl implements ITokenService {


    //原子引用，多线程安全
    private AtomicReference<String> tokenAtomic = new AtomicReference<>();

    @Value("token.id")
    private String tokenId;
    @Value("token.name")
    private String tokenName;

    @Override
    public String getToken() {
        if (StringUtils.isEmpty(tokenAtomic.get())){
            refreshToken();
        }
        return tokenAtomic.get();
    }


    //定时执行更新任务
    //@Scheduled(initialDelay = 1000, fixedDelay = 7 * 3600 * 1000)
    @Scheduled(initialDelay = 1000, fixedDelay =100*1000)
    private String refreshToken(){
        log.info("更新token");
        String token = TokenMgr.createJWT(tokenId,tokenName, GlobalConsts.JWT_EXPTIME);
        tokenAtomic.set(token);
        return token;
    }
}
